﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }

    <link href="/css/DeviceByTestYield.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>DeviceByTestYield</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        .Zebra {
            background-color: #e5ecff;
        }

        .ZebraNo {
            background-color: #e8f1f9;
        }

        .ZebraTo {
            background-color: #ffffff;
        }

        .warn {
            background-color: #ffcccc;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        .jobnum:hover {
            background-color: #b3f1fe;
        }

        /*END*/
        .truncate {
            max-width: 1.2rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            border-color: transparent;
        }

        /*选项卡*/
        .tab {
            overflow: hidden;
            width: 100%;
            /* height: 0.6rem; */
            /* padding: 0.1rem 0rem; */
        }

        .tab button {
            color: white;
            background-color: #0aa9cd;
            float: left;
            border: none;
            outline: none;
            cursor: pointer;
            font-size: 0.14rem;
            padding: 0.08rem 0.1rem;
            transition: 0.3s;
            border-bottom: 3px solid #509eb8;
        }

        .tab button:hover {
            background-color: #0aa9cd;
        }

        .tab button.active {
            color: white;
            background-color: #007297;
            border-bottom: 3px solid #0000ff;
            text-shadow: 0 0 0.2rem #00d8ff;
        }

        td.percentage {
            border-color: transparent;
        }
        /*end*/
        #btn_export {
            height: 0.3rem;
            font-size: 0.16rem;
            margin-left: 2px;
            border-radius: 2px;
            background-color: #e9e9ed;
            border: 1px solid #8f8f9d;
        }

        #btn_export:hover {
            background-color: #dddddd;
        }

        #Tab1 {
            /* border: 1px solid #59ebe8; */
            height: 9.2rem;
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }
    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="ProdExport('TesterYield')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/Retrospect.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        @Label.Note_EquipmentTestYield
                    </div>
                    <div id="board" class="chart">
                        <div class="query">
                            <span class="titleinput tle">@Label.Time:</span>
                            <input type="datetime-local" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time" style="width:1.9rem">
                            <span class="titleinput tle">@Label.To</span>
                            <input type="datetime-local" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="width: 1.9rem; margin-right: 0.1rem;">
                            <span class="titleinput tle">@Html.Raw(Label.Type):</span>
                            <select id="cmb_prod_type" placeholder="select ProdType">
                                <option value="ALL">@Label.ALL</option>
                                <option value="Normal">@Label.Fresh</option>
                                <option value="Rework">@Label.Rework</option>
                                <option value="RMA">@Label.RMA</option>
                            </select>
                            <span class="titleinput tle">Site:</span>
                            <select id="cmb_site" name="Site" placeholder="select Origin Site">
                                <option value="DG">@Label.DG</option>
                                <option value="AMT">@Label.AMT</option>
                            </select> 
                            <span class="titleinput tle">Project:</span>
                            <select id="cmb_proj_code" placeholder="select Origin Project"></select>
                            <span class="titleinput tle">@Html.Raw(Label.Process):</span>
                            <select id="cmb_process" placeholder="select Process"></select>
                            <span class="titleinput tle">Failure:</span>
                            <select id="cmb_failuregroup" placeholder="select Origin Failure"></select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                        </div>
                        <div style="height: 9.25rem;">
                            <div class="tab">
                                <div id="tab-center">
                                    @*
                                    <button class="tablinks active" onclick="OpenTab(event,'tab','Tab1',tablereport)">AATest&nbsp;BY&nbsp;YIELD</button>
                                    <button class="tablinks" onclick="OpenTab(event,'tab','Tab1',tablereport)">AssemblyTest&nbsp;BY&nbsp;YIELD</button>
                                    *@
                                </div>
                                @*
                                <div id="cmb_tester">
                                    <select id="cmb_tester_type">
                                        <option value="ALL">开发中</option>
                                    </select>
                                </div>
                                *@
                            </div>
                            <div id="Tab1">
                                <div id="tablereport"></div>
                                <div id="centerchart">
                                    <div id="select_btn">
                                        <div id="cmb_chart_data">
                                            <select id="cmb_chart_data_type">
                                                <option value="DAY">天</option>
                                                <option value="WEEK">周</option>
                                            </select>
                                        </div>
                                        <div id="cmb_chart_tester">
                                            <select id="cmb_chart_tester_type">
                                                <option value="ALL">@Label.ALL</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div id="reportchart"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        //模板初始化配置
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_EquipmentTestYield)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            // 设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    // 判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit + Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });
            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
        });

        var parameterdata;
        var GetComBoxParameter = function () {
            $.ajax({
                type: "POST",
                url: api + "/ReportAction/GetComBoxParameterTo",
                dataType: "json",
                async: false,
                success: function (response) {
                    parameterdata = response.ReturnData;
                    parameterbind(parameterdata);
                }
            });
        }

        function clearTabs() {
            $('#tab-center').empty();
        }

        function renderTabs(qpList) {
            const $tab = $('#tab-center').empty();
            if (!qpList || qpList.length === 0) {
                $tab.append('<button class="tablinks" disabled>— No Query Process —</button>');
                return;
            }
            qpList.forEach((q, i) => {
                const $btn = $('<button>', {
                    class: 'tablinks' + (i === 0 ? ' active' : ''),
                    name: q.value,
                    text: q.text || q.value
                })
                .data('value', q.value)
                .on('click', function(e){
                    //切换激活态
                    $tab.find('.tablinks').removeClass('active');
                    $(this).addClass('active');
                    //调用你的 OpenTab（保持原签名）
                    if (typeof OpenTab === 'function') {
                        OpenTab(e, 'tab', 'Tab1', window.tablereport);
                    }
                });
                $tab.append($btn);
            });
          //默认选中第一个：自动触发一次点击
          //$tab.find('.tablinks').first().trigger('click');
        }

        // ===== bind select =====
        function clearAndPlaceholder($sel, ph) {
            $sel.empty().append($('<option>', { value: '', text: ph || '— Select —' }));
        }
        function setOptions($sel, list, ph) {
            clearAndPlaceholder($sel, ph);
            $.each(list, function(_, o){
                $sel.append($('<option>', { value: o.value, text: o.text || o.value }));
            });
            //只有一个选项时自动选中并触发 change
            if (list.length === 1) {
                $sel.val(list[0].value).trigger('change');
            }
        }
        function uniqByValue(list){
            const seen = {};
            return list.filter(it => it && !seen[it.value] && (seen[it.value] = true));
        }

        function parameterbind (parameterdata){
            var dict = parameterdata;
            const $site = $('#cmb_site');
            const $proj = $('#cmb_proj_code');
            const $proc = $('#cmb_process');
            const $fail = $('#cmb_failuregroup');

            //初始清空下游
            clearAndPlaceholder($proj, '— Project —');
            clearAndPlaceholder($proc, '— Process —');
            clearAndPlaceholder($fail, '— Failure —');

            /* 1)site → project (保持你原有逻辑) */
            $site.on('change', function(){
                const site = $(this).val();
                const projList = dict.project
                .filter(p => p.site === site)
                .map(p => ({text:p.text, value:p.value}));
                setOptions($proj, uniqByValue(projList), '— Project —');
                clearAndPlaceholder($proc, '— Process —');
                clearAndPlaceholder($fail, '— Failure —');
                clearTabs();
                if ($proj.find('option').length > 1) { $proj.prop('selectedIndex', 1).trigger('change'); }
            });

            /* 2)project → process */
            $proj.on('change', function(){
                const site = $site.val();
                const proj = $proj.val();
                const procList = dict.process
                .filter(p => p.site === site && p.project === proj)
                .map(p => ({text:p.text, value:p.value}));
                setOptions($proc, uniqByValue(procList), '— Process —');
                clearAndPlaceholder($fail, '— Failure —');
                clearTabs();
                if ($proc.find('option').length > 1) { $proc.prop('selectedIndex', 1).trigger('change'); }
            });

            /* 3)process → failure */
            $proc.on('change', function(){
                const site = $site.val();
                const proj = $proj.val();
                const proc = $proc.val();
                const failList = dict.failure
                .filter(f => f.site === site && f.project === proj && f.process === proc)
                .map(f => ({text:f.text, value:f.value}));
                setOptions($fail, uniqByValue(failList), '— Failure —');
                clearTabs();
                if ($fail.find('option').length > 1) { $fail.prop('selectedIndex', 1).trigger('change'); }
            });

            /* 4) failure → query_process  渲染按钮页签 */
            $fail.on('change', function(){
                const site = $site.val();
                const proj = $proj.val();
                const proc = $proc.val();
                const fail = $fail.val();
                const qpList = dict.query_process
                .filter(q => q.site === site && q.project === proj && q.process === proc && q.failure === fail)
                .map(q => ({text:q.text, value:q.value}));
                //生成按钮第一个默认 active
                renderTabs(uniqByValue(qpList));
            });
            $site.trigger('change');
        }

        //定时查询
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔10m执行一次
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    getdate();
                }
            }, 10 * 60 * 1000);
        }

        $(function () {
            var startDate = new Date();
            startDate.setMonth(startDate.getMonth() - 1);
            startDate.setHours(7, 0, 0, 0);
            var endDate = new Date();
            endDate.setHours(7, 0, 0, 0);
            $('#startdate').val(startDate.toISOString().split('T')[0]);
            $('#enddate').val(endDate.toISOString().split('T')[0]);
            var startdatetime = startDate.toLocaleDateString('sv-SE') + 'T' + startDate.toTimeString().slice(0, 5);
            $('#startdate').val(startdatetime);
            var enddatetime = endDate.toLocaleDateString('sv-SE') + 'T' + endDate.toTimeString().slice(0, 5);
            $('#enddate').val(enddatetime);
            GetComBoxParameter();
            setTimeout(function () {
                Getdata();
            }, 500);
        })

        var Getdata = function () {
            getdate();
            TabInterval();
        }
        
        //报表导出
        var exporttype;
        var ProdExport = function (type) {
            exporttype = type;
            var formData = new FormData();
            formData.append('site', $('#cmb_site').val());
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('process_id', $("#cmb_process").val());
            formData.append('type', $('#cmb_prod_type').val());
            formData.append('start_time', $('#startdate').val());
            formData.append('end_time', $('#enddate').val());
            formData.append('deeect', $('#cmb_failuregroup').val());
            formData.append('filename', type);
            var url = api + "/ReportAction/TesterBackTestYieldToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = exporttype.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        function loadingshow() {
            $('#btn_query').prop('disabled', true);
            $("#select_btn").css("display", "none");
            $('#Tab1').css('background-image', 'url("../images/loading.gif")');
            $('#Tab1').css('background-size', '0.8rem 0.8rem');
            $('#Tab1').css('background-repeat', 'no-repeat');
            $('#Tab1').css('background-position', 'center');
        }
        function loadingnone() {
            $('#btn_query').prop('disabled', false);
            $("#select_btn").css("display", "block");
            $('#Tab1').css('background-image', 'none');
        }
        function getExcelColor(percentage) {
            let red, green;
            if (percentage <= 65) {
                red = 255;
                green = Math.round((percentage / 65) * 255);
            } else if (percentage <= 90) {
                green = 255;
                red = Math.round(255 - ((percentage - 75) / 30) * 200);
            } else {
                green = Math.round(255 - ((percentage - 90) / 10) * 50);
                red = Math.round(55 - ((percentage - 90) / 10) * 25);
            }
            return `rgb(${red}, ${green}, 150)`;
        }

        //获取数据
        var Tab;
        var getdate = function () {
            $("#tablereport").empty();
            $('#reportchart').css('background-color', 'transparent');
            echarts.dispose($("#reportchart").get(0));
            var header_key = {
                deeect: $('#cmb_failuregroup').val(),
                start_time: $('#startdate').val(),
                end_time: $('#enddate').val()
            };
            var pam = {};
            pam.site = $('#cmb_site').val();
            pam.proj_code = $('#cmb_proj_code').val();
            pam.process_id = $('#cmb_process').val();
            pam.type = $('#cmb_prod_type').val();
            pam.header_key = JSON.stringify(header_key);
            loadingshow();
            $.ajax({
                type: "POST",
                url: api + "/ReportAction/GetTesterBackTestYieldTo",
                data: pam,
                dataType: "json",
                async: true,
                success: function (dt) {
                    loadingnone();
                    Tab = dt.ReturnData;
                    uptablinks();
                    cmboxtype();
                    tablereport();
                }
            });
        }

        var current_page_data;
        function uptablinks() {
            var i, tablinks;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    tablinks[i].className = tablinks[i].className.replace("active", "");
                }
            }
            tablinks[0].className += " active";
            current_page_data = Tab.find(item => item.QUERY_PROCESS === tablinks[0].name);
        }

        /*Tab手动切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            var i, tablinks, fuc;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            current_page_data = Tab.find(item => item.QUERY_PROCESS === evt.currentTarget.name);
            cmboxtype()
            echar_name();
        }

        function CharstDataTypeMapping(selectDataType) {
            const typeMapping = {
                DAY: "ChartByDayYieldJson",
                WEEK: "ChartByWeekYieldJson"
            };
            const selectedKey = typeMapping[selectDataType];
            if (selectedKey && current_page_data[selectedKey]) {
                const parsedData = JSON.parse(current_page_data[selectedKey]);
                return parsedData;
            }
        }

        function cmboxtype(chartype) {
            var data = CharstDataTypeMapping("DAY");
            $('#cmb_chart_tester_type').empty().append('<option value="ALL">@Label.ALL</option>');
            const uniqueTesters = data.map(item => item.TESTER).filter((tester, index, self) => self.indexOf(tester) === index);
            const options = uniqueTesters.map(tester => `<option value="${tester}">${tester}</option>`).join('');
            $('#cmb_chart_tester_type').append(options);
        }

        //tester下拉
        $('#cmb_chart_tester_type,#cmb_chart_data_type').on('change', function () {
            var i, tablinks, fuc;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    tablereport();
                }
            }
        });

        var tablereport = function(){
            $('#btn_query').prop('disabled', false);
            $("#tablereport").empty();
            var data = JSON.parse(current_page_data.ReportJson);
            var tester_end_html = `
            <table id="reportdata" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="report_tbody"></tbody>
            </table>`;
            $("#tablereport").append(tester_end_html);
            var aatest_table = $('#reportdata');
            var aatest_tbody = aatest_table.find('tbody');
            $("#reportdata>thead>tr, #report_tbody,#reportdata>tfoot>tr").empty();
            // 动态生成表头
            var aatest_headerRow = aatest_table.find('thead tr');
            var aatest_headers = Object.keys(data[0]);
            aatest_headers.forEach(function (header) {
                aatest_headerRow.append('<th>' + header + '</th>');
            });
            // 生成表格内容
            data.forEach(function (row, index) {
                index++;
                var tdvaule;
                var newRow = $(`<tr class="${(index % 2) > 0 ? "ZebraNo" : "ZebraTo"}"></tr>`);
                aatest_headers.forEach(function (header, columnindex) {
                    tdvaule = row[header];
                    if (!["PROJ_CODE", "PROCESS_ID", "DATE"].includes(header)) {
                        if (row[header] == null || row[header] == "NULL") {
                            tdvaule = 'No Data';
                        }
                        else{
                            tdvaule = parseFloat(row[header]).toFixed(2) + '%';
                        }
                        newRow.append(`<td class="percentage">${tdvaule}</td>`);
                    }
                    else{
                        newRow.append(`<td class="truncate">${tdvaule}</td>`);
                    }

                });
                aatest_tbody.append(newRow);
            });
            $('.percentage').each(function() {
                const percentage = parseInt($(this).text().replace('%', ''), 10);
                $(this).css('background-color', getExcelColor(percentage));
            });
            futesteryieldchart();
        }
        //图表
        var testeryieldchart;
        var futesteryieldchart = function () {
            const selectedTester = $('#cmb_chart_tester_type').val();
            const selectDataType = $('#cmb_chart_data_type').val();
            var chartData = CharstDataTypeMapping(selectDataType);
            if (selectedTester != "ALL") {
                chartData = chartData.filter(item => item.TESTER === selectedTester);
            }
            updateChartOptions(chartData, null, 'reportchart');
        };
        var updateChartOptions = function (chartData, dataZoomConfig, ElementById) {
            $('#' + ElementById).css('background-color', 'transparent');
            var chartDom = document.getElementById(ElementById);
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var testeryieldchart = echarts.init(chartDom);
            const buildDataMap = (chartData) => {
                const dataItemMap = new Map();
                chartData.forEach(item => {
                    const key = item.DATE + '_' + item.TESTER;
                    dataItemMap.set(key, item);
                });
                return dataItemMap;
            };
            var allDays = Array.from(new Set(chartData.map(item => item.DATE)));
            var groupedData = {};
            chartData.forEach(function (item) {
                var yieldValue = parseFloat(item.YIELD) || 0;
                if (!groupedData[item.TESTER]) {
                    groupedData[item.TESTER] = {};
                }
                groupedData[item.TESTER][item.DATE] = yieldValue;
            });
            var seriesData = Object.keys(groupedData).map(function (tester) {
                var data = allDays.map(function (date) {
                    return groupedData[tester][date] !== undefined ? groupedData[tester][date] : null;
                });
                return {
                    name: tester,
                    type: 'line',
                    data: data,
                    tooltip: {
                        valueFormatter: function (value) {
                            if (value === null || value === undefined) {
                                return 'No Data';
                            }else{
                                return value.toFixed(2) + '%';
                            }
                        }
                    }
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        const dataItemMap = buildDataMap(chartData);
                        params.forEach(function (item) {
                            const key = item.axisValue + '_' + item.seriesName;
                            const dataItem = dataItemMap.get(key);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>Input: ${dataItem.INPUT}</td>
                                    <td>Output: ${dataItem.OUTPUT}</td>
                                    <td>Fail: ${dataItem.FAIL}</td>
                                    <td>Yield: ${dataItem.YIELD}%</td>
                                </tr>`;
                            } else {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td colspan="4">No Data</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    /*top: 10,*/
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '4%',
                    right: '2%',
                    bottom: '10%',
                    width: '94%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: allDays,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Yield(%)',
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value.toFixed(2) + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            testeryieldchart.setOption(option, true);
            window.addEventListener('resize', function () {
                testeryieldchart.resize();
            });
        };
        
    </script>
</body>
</html>
